package com.avecsys.quotemanager.mbeans.buyer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icefaces.ace.json.JSONException;
import org.icefaces.ace.json.JSONObject;

import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.BuyerMasterPojo;
import com.avecsys.quotemanager.pojos.BuyerUsersPojo;
import com.avecsys.quotemanager.pojos.SupplierMasterPojo;
import com.avecsys.quotemanager.pojos.SupplierUsersPojo;
import com.avecsys.quotemanager.service.buyer.BuyerMasterService;
import com.avecsys.quotemanager.service.common.CommonService;
import com.avecsys.quotemanager.service.supplier.SupplierMasterService;
import com.avecsys.quotemanager.service.user.UserMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.TransactionStatus;

/**
 * @author Sam Sundar
 * 
 */
public class BuyerUsersListMBean extends BaseMBean implements Serializable {
	private final Log log = LogFactory.getLog(BuyerUsersListMBean.class);

	private BuyerMasterPojo selectedBuyer;

	private BuyerMasterService buyerMasterService;

	private UserMasterService userMasterService;

	private CommonService commonService;

	private List<BuyerUsersPojo> buyerUsersPojoList = new ArrayList<BuyerUsersPojo>();

	public BuyerMasterPojo getSelectedBuyer()
	{
		return selectedBuyer;
	}

	public List<BuyerUsersPojo> getBuyerUsersPojoList()
	{
		return buyerUsersPojoList;
	}

	public void setBuyerUsersPojoList(List<BuyerUsersPojo> buyerUsersPojoList)
	{
		this.buyerUsersPojoList = buyerUsersPojoList;
	}

	public void setSelectedBuyer(BuyerMasterPojo selectedBuyer)
	{
		this.selectedBuyer = selectedBuyer;
	}

	public BuyerMasterService getBuyerMasterService()
	{
		return buyerMasterService;
	}

	public void setBuyerMasterService(BuyerMasterService buyerMasterService)
	{
		this.buyerMasterService = buyerMasterService;
	}

	public BuyerUsersListMBean() {
		super();
	}

	/**
	 * Action method to open the add user screen for a buyer
	 * 
	 * @return String
	 */
	public String actionAddUser() {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String selectedBuyerId = paramValues.get("selectedBuyerId");
		String selectedBuyerCompanyName = paramValues
				.get("selectedBuyerCompanyName");
		BuyerUsersMBean buyerUsersMBean = (BuyerUsersMBean) faceContext
				.getApplication().evaluateExpressionGet(faceContext,
						"#{buyerUsersMBean}", BuyerUsersMBean.class);
		buyerUsersMBean.setSelectedBuyerId(selectedBuyerId);
		buyerUsersMBean
				.setSelectedBuyerCompanyName(selectedBuyerCompanyName);
		buyerUsersMBean.setBuyerUsersPojo(new BuyerUsersPojo());
		return "openAddUserForBuyer";
	}

	public String actionCancel() {
		return "openListAllBuyers";
	}

	/**
	 * Method to delete the selected buyer user
	 * 
	 * @param actionEvent
	 */
	public void actionDeleteBuyerUser(ActionEvent actionEvent) {
		MessageBoardUtil.resetMessageBoard();
		String requestJSON = getMessageDialog().getRequestJSON();
		JSONObject requestJSONObject;
		String buyerUserId = null;
		try {
			requestJSONObject = new JSONObject(requestJSON);
			buyerUserId = (String) requestJSONObject.get("buyerUserId");
			BuyerUsersPojo buyerUsersPojo = userMasterService
					.getBuyerUserById(new Long(buyerUserId));
			BuyerMasterPojo buyerMasterPojo = buyerUsersPojo
					.getBuyerMasterPojo();
			TransactionStatus transactionStatus = userMasterService
					.deleteBuyerUser(buyerUsersPojo);
			loadAllUsersByBuyer(buyerMasterPojo);
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.SUPPLIER_USER, "messageBoardId", "",
					new Object[] { buyerUsersPojo.getUserMasterPojo()
							.getUserName() });
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		getMessageDialog().hideDialog();
	}

	/**
	 * Action Method to send verification email to Buyer user
	 * 
	 * @param actionEvent
	 */
	public void actionSendVerificationEmail(ActionEvent actionEvent) {
		MessageBoardUtil.resetMessageBoard();
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String buyerUserId = (String) paramValues.get("buyerUserId");
		BuyerUsersPojo buyerUsersPojo = null;
		try {
			buyerUsersPojo = userMasterService.getBuyerUserById(new Long(
					buyerUserId));
			// Send Verification Email only when if it is not already verified
			commonService.sendEmail(buyerUsersPojo);
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		try {
			if (buyerUsersPojo != null) {
				loadAllUsersByBuyer(buyerUsersPojo
						.getBuyerMasterPojo());
			}
		} catch (BusinessException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
	}

	/**
	 * Method to show the confirm dialog request to delete Buyer user
	 * 
	 * @param actionEvent
	 */
	public void confirmDeleteAction(ActionEvent actionEvent) {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String buyerUserId = (String) paramValues.get("buyerUserId");
		String selectedBuyerId = (String) paramValues
				.get("selectedBuyerId");
		String userName = (String) paramValues.get("userName");
		JSONObject requestJSONObject = new JSONObject();
		try {
			requestJSONObject.put("buyerId", selectedBuyerId);
			requestJSONObject.put("buyerUserId", buyerUserId);
			requestJSONObject.put("companyName", userName);
			getMessageDialog().setRequestJSON(requestJSONObject.toString());
			getMessageDialog().setMessage(
					"Are you sure to delete '" + userName + "' ?");
		} catch (JSONException e) {
			log.error(e);
		}
		getMessageDialog().showDialog();
	}

	/**
	 * Edits the Buyer user information
	 * 
	 * @return
	 */
	public String editBuyerUser() {
		FacesContext faceContext = FacesContext.getCurrentInstance();
		Map<String, String> paramValues = faceContext.getExternalContext()
				.getRequestParameterMap();
		String selectedBuyerId = paramValues.get("selectedBuyerId");
		String selectedBuyerCompanyName = paramValues
				.get("selectedBuyerCompanyName");
		String buyerUserId = (String) paramValues.get("buyerUserId");
		try {
			BuyerUsersMBean buyerUsersMBean = (BuyerUsersMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{buyerUsersMBean}", BuyerUsersMBean.class);
			buyerUsersMBean.setSelectedBuyerId(selectedBuyerId);
			buyerUsersMBean
					.setSelectedBuyerCompanyName(selectedBuyerCompanyName);
			BuyerUsersPojo buyerUsersPojo = userMasterService
					.getBuyerUserById(Long.parseLong(buyerUserId));
			buyerUsersMBean.setBuyerUsersPojo(buyerUsersPojo);
			// preserve the the email address to identify user has changed the
			// email address
			buyerUsersMBean.setExistingEmailAddress(buyerUsersPojo
					.getUserMasterPojo().getEmail());
			buyerUsersMBean.setScreenModeEdit(true);
		} catch (BusinessException e) {
			log.error(e);
		} catch (Exception e) {
			log.error(e);
		}
		return "openEditUserForBuyer";
	}

	public CommonService getCommonService() {
		return commonService;
	}



	/**
	 * @return the userMasterService
	 */
	public UserMasterService getUserMasterService() {
		return userMasterService;
	}

	/**
	 * Method to load all the users for a Buyer
	 * 
	 * @param buyerMasterPojo
	 * @throws BusinessException
	 */
	public void loadAllUsersByBuyer(BuyerMasterPojo buyerMasterPojo)
			throws BusinessException {
		setBuyerUsersPojoList(buyerMasterService
				.getAllUsers(buyerMasterPojo));
		setSelectedBuyer(buyerMasterPojo);
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * @param userMasterService
	 *            the userMasterService to set
	 */
	public void setUserMasterService(UserMasterService userMasterService) {
		this.userMasterService = userMasterService;
	}
}
